package es.us.lsi.daw.soportePropiedades;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JsonConfig;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.view.json.JsonWriterConfiguratorTemplateRegistry;
import org.springframework.web.servlet.view.json.writer.jsonlib.JsonlibJsonWriterConfiguratorTemplate;

import es.us.lsi.daw.dao.DAOAcceso;
import es.us.lsi.daw.model.security.Authority;
import es.us.lsi.daw.model.security.Group;
import es.us.lsi.daw.model.security.enums.GroupEnum;
import es.us.lsi.daw.util.UtilBinding;

public class BindingInitializer extends DAOAcceso implements WebBindingInitializer {

	public static final String	PETICION_AJAX	= "peticionAjax";

	public void initBinder(WebDataBinder binder, WebRequest request) {

		HttpServletRequest servletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		Boolean peticionAjax = (Boolean) servletRequest.getAttribute(PETICION_AJAX);
		if (peticionAjax == null) {
			peticionAjax = false;
		}

		SimpleDateFormat fmtFch = new SimpleDateFormat("dd/MM/yyyy");
		fmtFch.setLenient(false);

		if (!peticionAjax) {
			// Fechas y calendar
			binder.registerCustomEditor(Date.class, new CustomDateEditor(fmtFch, true));
			binder.registerCustomEditor(Calendar.class, new CalendarEditor());

			// TIpos Enumerados
			binder.registerCustomEditor(GroupEnum.class, new GroupEnumEditor());
			binder.registerCustomEditor(Group.class, new GroupEditor(daoAuthorization));
			binder.registerCustomEditor(Authority.class, new ComunEditor(Authority.class, daoComun));
			
		}
		JsonWriterConfiguratorTemplateRegistry registry = JsonWriterConfiguratorTemplateRegistry.load(servletRequest);

		registry.registerConfiguratorTemplate(new JsonlibJsonWriterConfiguratorTemplate() {

			@Override
			public JsonConfig getJsonConfig() {

				return new UtilBinding().getJsonConfigComun();
			}
		});
	}
}
